package com.jams.goodox.activity.mine.settings;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.entity.resp.InvoiceResp;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.EditTextWithDel;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

import static com.jams.goodox.utils.StringUtils.newString;


/**
 * 开票设置
 */
public class InvoiceFragment extends BaseFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.et_enterprise_name)
    EditTextWithDel etEnterpriseName;
    @Bind(R.id.et_enterprise_tax_number)
    EditTextWithDel etEnterpriseTaxNumber;
    @Bind(R.id.et_enterprise_register_address)
    EditTextWithDel etEnterpriseRegisterAddress;
    @Bind(R.id.et_enterprise_register_phone)
    EditTextWithDel etEnterpriseRegisterPhone;
    @Bind(R.id.et_enterprise_deposit_bank)
    EditTextWithDel etEnterpriseDepositBank;
    @Bind(R.id.et_enterprise_bank_account)
    EditTextWithDel etEnterpriseBankAccount;
    @Bind(R.id.ll_value_added_tax)
    LinearLayout llValueAddedTax;
    @Bind(R.id.submit)
    TextView submit;
    Map<String, String> paramsCommon = new HashMap<>();
    Map<String, String> paramsSpecial = new HashMap<>();

    private String mParam1;
    private String userId;
    private Animation shake;
    public InvoiceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment InvoiceFragment.
     */
    public static InvoiceFragment newInstance(String param1, String userId) {
        InvoiceFragment fragment = new InvoiceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            userId = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_invoice, container, false);
        shake = AnimationUtils.loadAnimation(mActivity, R.anim.shake_left_right);
        ButterKnife.bind(this, view);
        if ("0".equals(mParam1)) {
            llValueAddedTax.setVisibility(View.GONE);
        } else if ("1".equals(mParam1)) {
            llValueAddedTax.setVisibility(View.VISIBLE);
        }
        myInvoice();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.submit)
    public void onViewClicked() {
        submit();
    }

    private void submit() {
        try {
            
            String name = StringUtils.newString(etEnterpriseName.getText().toString().trim());//企业名称
            String taxNo = StringUtils.newString(etEnterpriseTaxNumber.getText().toString().trim()); //企业税号
            String address = StringUtils.newString(etEnterpriseRegisterAddress.getText().toString().trim());//企业注册地址
            String phone = StringUtils.newString(etEnterpriseRegisterPhone.getText().toString().trim());//企业注册电话
            String depositBank = StringUtils.newString(etEnterpriseDepositBank.getText().toString().trim());//企业开户银行
            String bankAccount = StringUtils.newString(etEnterpriseBankAccount.getText().toString().trim());//企业银行账号
            if (TextUtils.isEmpty(name) || name.length() < 2) {
                etEnterpriseName.startAnimation(shake);
                ToastUtil.show(mContext, R.string.enterprise_full_name);
                return;
            }
            final String taxReg = "[A-Za-z0-9]{18}";//税号18位,允许数字,英文字母
            Pattern idTaxPattern = Pattern.compile(taxReg);
            Matcher idTaxMatcher = idTaxPattern.matcher(taxNo);
            if (!idTaxMatcher.matches()) {
                etEnterpriseTaxNumber.startAnimation(shake);
                ToastUtil.show(mContext, R.string.error_tip_enterprise_tax_number);
                return;
            }
            if ("1".equals(mParam1)) {
                if (TextUtils.isEmpty(address) || address.length() < 4) {
                    etEnterpriseRegisterAddress.startAnimation(shake);
                    ToastUtil.show(mContext, R.string.tip_enterprise_register_address);
                    return;
                }
                
                final String phoneReg = "\\d{3,4}(-|—)\\d{7,8}";//座机号0571-88888888"
                Pattern idNumPattern = Pattern.compile(phoneReg);
                Matcher idNumMatcher = idNumPattern.matcher(phone);
                if (!idNumMatcher.matches()) {
                    etEnterpriseRegisterPhone.startAnimation(shake);
                    ToastUtil.show(mContext, R.string.tip_enterprise_register_phone);
                    return;
                }
                if (TextUtils.isEmpty(depositBank) || depositBank.length() < 2) {
                    etEnterpriseDepositBank.startAnimation(shake);
                    ToastUtil.show(mContext, R.string.tip_enterprise_deposit_bank);
                    return;
                }
                if (TextUtils.isEmpty(bankAccount) || bankAccount.length() < 6) {
                    etEnterpriseBankAccount.startAnimation(shake);
                    ToastUtil.show(mContext, R.string.tip_enterprise_bank_account);
                    return;
                }

            }
            if ("0".equals(mParam1)) {//普通发票
                paramsCommon.put("enterpriseNameNormal", name);//公司名称
                paramsCommon.put("enterpriseNoNormal",taxNo);//公司税号
                normalInvoice();
            } else if ("1".equals(mParam1)) {//专用发票
                paramsSpecial.put("enterpriseAddress", address);
                paramsSpecial.put("enterpriseBank", depositBank);
                paramsSpecial.put("enterpriseBankAccount", bankAccount);
                paramsSpecial.put("enterpriseNameSpecial", name);
                paramsSpecial.put("enterpriseNo", taxNo);
                paramsSpecial.put("enterprisePhone", phone);
                specialInvoice();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 普通发票
     */
    private void normalInvoice() {
        showLoading();
        enqueue(createCallService(EnterpriseService.class).normalInvoice(paramsCommon), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                misLoading();
                ToastUtil.show(mContext, "提交成功");
                mActivity.finish();
            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }

    /**
     * 专用发票
     */
    private void specialInvoice() {
        showLoading();
        enqueue(createCallService(EnterpriseService.class).specialInvoice(paramsSpecial), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                misLoading();
                ToastUtil.show(mContext, "提交成功");
                mActivity.finish();
            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }

    /**
     * 我的开票设置
     */
    private void myInvoice() {
        showLoading();
        enqueue(createCallService(EnterpriseService.class).myInvoice(userId), new RetrofitCallbackListener<InvoiceResp>() {
            @Override
            public void onSuccess(Call<InvoiceResp> call, InvoiceResp result) {
               
                misLoading();
                try { 
                    InvoiceResp.DataBean data = result.data;
                    if (data != null) {
                        etEnterpriseName.setText(newString(data.enterpriseNameNormal));//普通发票
                        etEnterpriseTaxNumber.setText(newString(data.enterpriseNoNormal));
                        if ("1".equals(mParam1)) {//专用发票
                            etEnterpriseTaxNumber.setText(newString(data.enterpriseNo));
                            etEnterpriseRegisterAddress.setText(newString(data.enterpriseAddress));
                            etEnterpriseDepositBank.setText(newString(data.enterpriseBank));
                            etEnterpriseBankAccount.setText(newString(data.enterpriseBankAccount));
                            etEnterpriseName.setText(newString(data.enterpriseNameSpecial));
                            etEnterpriseRegisterPhone.setText(newString(data.enterprisePhone));
                        }
                        etEnterpriseName.setSelection(etEnterpriseName.getText().length());
                        etEnterpriseTaxNumber.setSelection(etEnterpriseTaxNumber.getText().length());
                        etEnterpriseRegisterAddress.setSelection(etEnterpriseRegisterAddress.getText().length());
                        etEnterpriseDepositBank.setSelection(etEnterpriseDepositBank.getText().length());
                        etEnterpriseBankAccount.setSelection(etEnterpriseBankAccount.getText().length());
                        etEnterpriseRegisterPhone.setSelection(etEnterpriseRegisterPhone.getText().length());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }

}
